/*
 * Copyright (c) 2020 Fraunhofer FOKUS and others. All rights reserved.
 *
 * See the NOTICE file(s) distributed with this work for additional
 * information regarding copyright ownership.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License 2.0 which is available at
 * http://www.eclipse.org/legal/epl-2.0
 *
 * SPDX-License-Identifier: EPL-2.0
 *
 * Contact: mosaic@fokus.fraunhofer.de
 */

package org.eclipse.mosaic.fed.mqtt.callback;

import org.eclipse.mosaic.fed.mqtt.ambassador.MqttAmbassador;
import org.eclipse.mosaic.fed.mqtt.message.AbstractMqttMessage;
import org.eclipse.mosaic.fed.mqtt.message.MqttMessageFactory;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Default Callback for mqtt client
 * when configuration did not specify the callback method
 */
public class DefaultCallback implements MqttCallback {

    private static final Logger log = LoggerFactory.getLogger(DefaultCallback.class);

    private MqttAmbassador mqttAmbassador;

    public DefaultCallback(MqttAmbassador mqttAmbassador) {
        this.mqttAmbassador = mqttAmbassador;
    }

    @Override
    public void connectionLost(Throwable throwable) {
        log.error("Mqtt client connect lost.", throwable);
    }

    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
        String payload = mqttMessage.toString();

        log.info("received message {} from topic {}", payload, topic);

        AbstractMqttMessage message = MqttMessageFactory.INSTANCE.getMqttMessage(topic, payload);

        mqttAmbassador.store(topic, message.getId(), message);
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        try {
            log.info("Message delivery complete, message id : {}", iMqttDeliveryToken.getMessage().toString());
        } catch (MqttException e) {
            throw new RuntimeException(e);
        }
    }
}
